import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Platform,
  StatusBar,
  FlatList,
  RefreshControl,
} from 'react-native';
import React, {useState, useEffect} from 'react';
import {useNavigation, useTheme} from '@react-navigation/native';
import NavigationBar from '../../components/NavigationBar.jsx';
import Icon from '@react-native-vector-icons/ionicons';
import Tooltip from 'react-native-walkthrough-tooltip';
import isEmpty from 'lodash/isEmpty';
import {useSelector, useDispatch} from 'react-redux';
import {changeTrendingData, fetchTrending} from '../../store/trending.js';
import PopularItem from '../../components/PopularItem.jsx';
import Refresh from '../../components/Refresh.jsx';

const sinceList = [
  {
    label: '今日',
    value: 'daily',
  },
  {
    label: '本周',
    value: 'weekly',
  },
  {
    label: '本月',
    value: 'monthly',
  },
];
export default function TrendingPage() {
  const trending = useSelector(state => state.trending);
  const dispatch = useDispatch();

  const navigation = useNavigation();
  const colors = useTheme();
  const [visible, setVisible] = useState(false);
  const [since, setSince] = useState(sinceList[0].label);

  function getKey() {
    return sinceList.find(item => item.label === since).value;
  }

  useEffect(() => {
    if (isEmpty(trending.trendingData[getKey()])) {
      dispatch(fetchTrending({key: getKey()}));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [since]);

  function handleClick(item) {
    setSince(item.label);
    setVisible(false);
  }

  function handlePress() {
    setVisible(true);
  }

  const handleRefresh = () => {
    dispatch(fetchTrending({key: getKey(), refresh: true}));
  };

  const handleEndReached = () => {
    console.log('22221');
  };

  const changeFavorite = item => {
    dispatch(changeTrendingData({item, key: getKey()}));
  };

  const handleClickItem = item => {
    navigation.navigate('Detail', {item});
  };

  const sinceView = (
    <View style={styles.sinceView}>
      {sinceList.map(item => (
        <TouchableOpacity
          onPress={() => handleClick(item)}
          key={item.value}
          style={styles.sinceItem}>
          <Text style={[styles.sinceText, {color: colors.primary}]}>
            {item.label}
          </Text>
        </TouchableOpacity>
      ))}
    </View>
  );

  const renderItem = ({item}) => {
    return (
      <PopularItem
        item={item}
        changeFavorite={changeFavorite}
        onClickItem={handleClickItem}
      />
    );
  };

  return (
    <>
      <NavigationBar
        titleView={
          <Tooltip
            isVisible={visible}
            showChildInTooltip={false}
            topAdjustment={
              Platform.OS === 'android' ? -StatusBar.currentHeight : 0
            }
            content={sinceView}
            placement="bottom"
            onClose={setVisible}>
            <TouchableOpacity
              style={styles.titleView}
              activeOpacity={1}
              onPress={handlePress}>
              <Text style={styles.title}>{`趋势 ${since}`}</Text>
              <Icon name="caret-down-sharp" color="white" size={20} />
            </TouchableOpacity>
          </Tooltip>
        }
      />
      {!isEmpty(trending.trendingData[getKey()]) ? (
        <FlatList
          refreshControl={
            <RefreshControl
              colors={['tomato']}
              refreshing={trending.refresh}
              onRefresh={handleRefresh}
            />
          }
          onEndReached={handleEndReached}
          onEndReachedThreshold={0.5}
          ListFooterComponent={<Refresh content="正在加载更多" />}
          data={trending.trendingData[getKey()]}
          keyExtractor={item => item.id}
          renderItem={renderItem}
        />
      ) : (
        <Refresh fullScreen />
      )}
    </>
  );
}

const styles = StyleSheet.create({
  titleView: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  title: {
    fontSize: 18,
    fontWeight: '400',
    color: 'white',
    marginRight: 4,
  },
  sinceText: {
    textAlign: 'center',
    fontSize: 20,
  },
  sinceView: {
    flexDirection: 'column',
    flex: 1,
  },
  sinceItem: {
    flex: 1,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    paddingVertical: 4,
    paddingHorizontal: 20,
  },
});
